import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';

import { DataSource, Repository } from 'typeorm';
import { UploadEntity } from './entity/upload.entity';
import * as path from 'path';
import { writeFile } from 'fs/promises';

@Injectable()
export class UploadService {
  // process.cwd()方法是流程模块的内置应用程序编程接口，用于获取node.js流程的当前工作目录
  private readonly productLocation = process.cwd();
  private isAbsPath = false;
  constructor(
    private readonly configService: ConfigService,
    @InjectRepository(UploadEntity)
    private readonly uploadRepository: Repository<UploadEntity>,
    private readonly connection: DataSource,
  ) {
    this.isAbsPath = path.isAbsolute(
      process.env.file_location ? process.env.file_location : '',
    );
  }

  // 上传文件
  async create(
    files: Express.Multer.File[],
    remarks: string,
    user: { id: string; account: string },
  ): Promise<any> {
    await this.connection.manager.transaction(async (manager) => {
      return await manager.save(files);
    });
    return {
      files,
      remarks,
      user,
    };
  }

  async uploadFile(file: any): Promise<any> {
    const filePath = `${this.configService.get<string>('UPLOAD_FOLDER')}/${
      file.originalname
    }`;
    try {
      await writeFile(filePath, file.buffer);
      return {
        success: true,
        message: `File ${file.originalname} uploaded successfully`,
      };
    } catch (err) {
      return {
        success: false,
        message: `File ${file.originalname} upload failed, please retry`,
      };
    }
  }
}
